import { ref, reactive } from 'vue';
import { showToast } from 'vant';
import { http } from '@/utils/http';
import { useI18n } from 'vue-i18n';

export function useFileList(route, router) {
  const { t } = useI18n();
  const loading = ref(false);
  const pullLoading = ref(false);
  const files = reactive<any[]>([]);
  const images = reactive<string[]>([]);
  const previewShow = ref(false);
  const startPosition = ref(0);

  const loadFiles = async () => {
    loading.value = true;
    try {
      const res = await http.request<{
        data: {
          files: any[];
        };
      }>({
        url: `/api/storage/files`,
        method: 'post',
        data: {
          storageKey: '1',
          password: '',
          companyId: route.query.id,
          orderBy: 'name',
          path: route.query.path,
          orderDirection: 'asc',
          driveId: 'b!QDHl6VUBNkuolthEBSvGKl1QIodv6IlOlRLJhW20XoINDpdFyl-IQI_7IDPhkoPh',
        },
      });

      files.splice(0, files.length, ...res.data.files);
      files.forEach((item) => {
        item.icon = getFileIconName(item);
      });
    } catch (e) {
      console.error(`❌ ${t('detail.requestError')}:`, e);
    } finally {
      loading.value = false;
    }
  };

  const clickFile = async (i: any, companyInfo: { id?: string } = {}) => {
    if (i.type === 'FOLDER') {
      const folderPath = i.path ? i.path + '/' + i.name : route.query.path ? route.query.path + '/' + i.name : i.name;
      const companyId = companyInfo.id || route.query.id;
      const navTitle = i.alias || i.name;

      router.push({
        path: '/files',
        query: {
          path: folderPath,
          id: companyId,
          navTitle,
        },
      });
    } else if (i.icon === 'pdf') {
      router.push({
        path: '/pdfViewer',
        query: {
          url: i.url,
          navTitle: t('detail.pdfPreview'),
        },
      });
    } else if (i.icon === 'image') {
      previewShow.value = true;
      const imagesF = files.filter((f) => f.icon === 'image').map((f) => f.url);
      images.splice(0, images.length, ...imagesF);

      startPosition.value = files.findIndex((f) => f.icon === 'image' && f.name === i.name && f.url === i.url);
    } else {
      showToast(t('detail.notSupported'));
    }
  };

  const fileTypeMap = {
    image: ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp', 'ico'],
    video: ['mp4', 'webm', 'm3u8', 'rmvb', 'avi', 'swf', '3gp', 'mkv', 'flv'],
    audio: ['mp3', 'wav', 'wma', 'ogg', 'aac', 'flac', 'm4a'],
    text: ['txt', 'md', 'js', 'ts', 'java', 'py', 'html', 'css'],
    archive: ['zip', 'rar', '7z', 'tar', 'gz'],
    pdf: ['pdf'],
    office: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'],
  };

  function getFileSuffix(name: string) {
    const lastIndex = name.lastIndexOf('.');
    return lastIndex === -1 ? 'other' : name.substring(lastIndex + 1).toLowerCase();
  }

  function getFileType(name: string) {
    const suffix = getFileSuffix(name);
    for (const key in fileTypeMap) {
      if (fileTypeMap[key].includes(suffix)) return key;
    }
    return 'file';
  }
  function getFileIconName(file: any) {
    if (file.type === 'FOLDER' || file.type === 'ROOT' || file.type === 'BACK') {
      return file.type.toLowerCase();
    }
    const suffix = getFileSuffix(file.name);
    const type = getFileType(file.name);

    if (fileTypeMap.image.includes(suffix)) {
      return 'image';
    } else if (fileTypeMap.pdf.includes(suffix)) {
      return 'pdf';
    } else if (type) {
      return type;
    }
    return 'file';
  }

  return {
    files,
    images,
    previewShow,
    startPosition,
    loading,
    pullLoading,
    loadFiles,
    clickFile,
    getFileIconName,
  };
}
